package com.dlx.acl.service.impl;

import com.alibaba.nacos.common.utils.Objects;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlx.acl.mapper.UserMapper;
import com.dlx.acl.service.UserService;
import com.dlx.common.exception.SmmsException;
import com.dlx.common.result.Result;
import com.dlx.mem.client.MemInfoFeignClient;
import com.dlx.model.acl.User;
import com.dlx.model.mem.MemInfo;
import com.dlx.vo.acl.UserRegisterVo;
import com.dlx.vo.acl.UserUpdateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private MemInfoFeignClient memInfoFeignClient;

    @Override
    public User selectByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("username", username).or().eq("email", username).or().eq("mobile",username);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public Boolean register(UserRegisterVo userRegisterVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email", userRegisterVo.getEmail()).or().eq("mobile", userRegisterVo.getMobile());
        User user = this.baseMapper.selectOne(wrapper);
        if (Objects.nonNull(user)) {
            throw new SmmsException(201, "用户邮箱或手机号已存在");
        }
        User newUser = new User();
        BeanUtils.copyProperties(userRegisterVo, newUser);
        int insert = this.baseMapper.insert(newUser);
        return insert > 0;
    }

    /**
     * 更新用户信息
     *
     * @param userUpdateVo 用户更新签证官
     * @return {@link Boolean}
     */
    @Override
    public Boolean updateUserInfo(UserUpdateVo userUpdateVo) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = this.selectByUsername(username);
        BeanUtils.copyProperties(userUpdateVo, user);
        int i = this.baseMapper.updateById(user);
        MemInfo memInfo = new MemInfo();
        BeanUtils.copyProperties(userUpdateVo, memInfo);
        Result result = memInfoFeignClient.updateMemInfoByUserId(memInfo);
        return i > 0 && result.getCode() == 200;
    }

    @Override
    public User getCurrentUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return this.selectByUsername(username);
    }
}
